<template>
	<div class="login-container">
		<div class="login-form-box">
			<!-- 确保你的输入是合法 -->
			<el-form
				:model="ruleForm"
				ref="ruleForm"
				label-width="60px"
				:rules="rules"
			>
				<el-form-item label="账号" prop="account">
					<el-input v-model="ruleForm.account"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="ruleForm.password" type="password"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button
						class="button"
						type="primary"
						@click="submitForm('ruleForm')"
						>登录</el-button
					>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>
<script>
import { post } from '_api/http';
export default {
	data() {
		return {
			ruleForm: {
				account: '',
				passord: '',
			},
			rules: {
				account: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
				password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
			},
		};
	},
	methods: {
		async handleLogin() {
			// 发送登录
			const res = await post('/api/user/login', {
				account: this.ruleForm.account,
				password: this.ruleForm.password,
			});
			if (res.status) {
				// 登录成功，跳转到主页
				localStorage.setItem('token', res.data.token);
				localStorage.setItem('user', JSON.stringify(res.data.user));
				this.$message.success('登录成功');
				this.$router.replace('/home');
			} else {
				// 登录失败，提示错误信息
				this.$message.error(res.message);
			}
		},
		submitForm(formName) {
			//1.进行前端输入框校验
			this.$refs[formName].validate((valid) => {
				if (valid) {
					//2.校验成功，发送请求
					this.handleLogin();
				} else {
					//3.校验失败，提示错误信息
					this.$message.error('请输入正确的用户名和密码');
					return false;
				}
			});
		},
	},
};
</script>
<style scoped lang="less">
.login-container {
	width: 100%;
	height: 100vh;
	background-image: url('../../assets/bg1.jpg');
	background-size: cover;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}
.login-form-box {
	width: 350px;
	padding: 40px;
	background-color: rgba(173, 216, 230, 0.8);
	margin: 0 auto;
	text-align: center;
	border-radius: 10px;
	display: flex;
	justify-content: center;
	align-items: center;
}
.login-form {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}
.button {
	transform: translateX(-30px);
}
</style>
